package com.itheima.reggie.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    //进入controller之前进行身份校验
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取出employee对象
        Employee employee = (Employee)request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
        //session中没有这个员工对象时放行
        if (employee!=null){
            //用户合法的话，将其放到ThreadLocal中
            EmployeeHolder.set(employee);
            return true;
        }
        //session中有这个员工对象时不放行
        ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
        String json = new ObjectMapper().writeValueAsString(resultInfo);
        response.getWriter().write(json);
        //禁止通行
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
